import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Select, Button, Card, InputNumber, DatePicker, Tooltip, Icon, Cascader } from 'antd';


const FormItem = Form.Item;

@connect(state => ({
  packages: state.packages,
  general: state.general,
}))
@Form.create()
export default class AddPackage extends PureComponent {
  state = {

  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'general/getNetworkSpeedList',
      payload: {
        dictGroupCode: 'NETWORK_SPEED',
      },
    });
    dispatch({
      type: 'general/getBussinessLists',
      payload: {

      },
    });
    dispatch({
      type: 'general/getProvincesList',
      payload: {

      },
    });
  }
  /*
    处理表单数据
   */
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        /*
          成功后调用表单清除
         */
        const releaseValue = values.releaseTime || undefined;
        const invalidValue = values.invalidTime || undefined;
        this.props.dispatch({
          type: 'packages/addPackage',
          payload: {
            releaseTime: releaseValue && releaseValue.valueOf(),
            invalidTime: invalidValue && invalidValue.valueOf(),
            contractRate: values.contractRate,
            packageAttention: values.packageAttention,
            packageDescription: values.packageDescription,
            serviceDescription: values.serviceDescription,
            packageValidTime: values.packageValidTime,
            packageCommunities: values.serviceCommunity,
            networkSpeed: values.networkSpeed,
            packagePrice: values.packagePrice,
            packageName: values.packageName,
            bussinessId: values.bussinessId,
          },
          callback: () => {
            this.props.closeModal(true);
          },
        });
      }
    });
  }
  handleSelectCity = () => {
    this.props.form.setFieldsValue({
      serviceCommunity: undefined,
    });
  };
  handleDistrictFocus = () => {
    if (this.props.form.getFieldValue('cityName')) {
      const districtId = this.props.form.getFieldValue('cityName')[this.props.form.getFieldValue('cityName').length - 1];
      this.props.dispatch({
        type: 'general/getCommunityList',
        payload: {
          countyId: districtId,
        },
      });
    }
  }
  render() {
    const { general: { networkSpeedList },
      general: { bussinessLists, provincesList, communityList } } = this.props;
    const communityArray = [];
    communityList.map((item) => {
      return (
        communityArray.push({ id: item.id, value: item.communityName })
      );
    });
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };
    const networkSpeed = [];
    networkSpeedList.map(item => (
      networkSpeed.push(
        <Select.Option
          key={item.dictItemName}
          value={item.dictItemName}
        >{item.dictItemName}M
        </Select.Option>)
    ));
    const bussinessChildren = [];
    bussinessLists.map(item => (
      bussinessChildren.push(
        <Select.Option
          key={item.id}
          value={item.id}
        >{item.bussinessName}
        </Select.Option>)
    ));
    const dateFormat = 'YYYY/MM/DD';
    return (
      <Card bordered={false}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem
            {...formItemLayout}
            label="套餐名称"
          >
            {getFieldDecorator('packageName', {
              rules: [
                {
                  required: true, message: '请输入套餐名称',
                }],
            })(
              <Input placeholder="请输入套餐名称" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="业务类型"
          >
            {getFieldDecorator('bussinessId', {
              initialValue: bussinessLists[0] && bussinessLists[0].id,
              rules: [{
                required: true, message: '请选择业务类型',
              }],
            })(
              <Select placeholder="请选择业务类型">
                {bussinessChildren}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="城市"
          >
            {getFieldDecorator('cityName', {
              rules: [{
                required: true, message: '请选择城市',
              }],
            })(
              <Cascader
                onChange={() => { this.handleSelectCity(); }}
                size="large"
                style={{ width: '100%' }}
                options={provincesList}
                placeholder="请选择城市"
              />)}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="小区"
          >
            {getFieldDecorator('serviceCommunity', {
              rules: [{
                required: true, message: '请选择覆盖小区',
              }],
            })(
              <Select onFocus={() => { this.handleDistrictFocus(); }} mode="multiple" style={{ width: '100%' }} placeholder="请选择服务区域">
                {
                  communityArray.map((item, index) => {
                  return (
                    <Select.Option
                      key={index.toString()}
                      value={item.id}
                    >
                      {
                    item.value
                  }
                    </Select.Option>
                  );
                })
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="套餐价格"
          >
            {getFieldDecorator('packagePrice', {
              rules: [
                {
                  required: true, message: '请输入套餐价格',
                }],
            })(
              <InputNumber
                style={{ width: '100%' }}
                parser={value => value.replace(/\$\s?|(,*)/g, '')}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="下行网速"
            hasFeedback
          >
            {getFieldDecorator('networkSpeed', {
              rules: [
                {
                  required: true, message: '请选择下行网速',
                }],
            })(
              <Select
                style={{ width: '100%' }}
                placeholder="请选择下行网速"
              >
                {networkSpeed}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="套餐时长(按月算)"
          >
            {getFieldDecorator('packageValidTime', {
              rules: [
                {
                  required: true, message: '请输入套餐时长',
                }],
            })(
              <InputNumber
                style={{ width: '100%' }}
                parser={value => value.replace(/\$\s?|(,*)/g, '')}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="上架时间"
          >
            {getFieldDecorator('releaseTime', {
              rules: [
                {
                  required: true, message: '请选择上架时间',
                }],
            })(
              <DatePicker format={dateFormat} style={{ width: '100%' }} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="下架时间"
          >
            {getFieldDecorator('invalidTime', {
              rules: [
                {
                  required: true, message: '请选择下架时间',
                }],
            })(
              <DatePicker format={dateFormat} style={{ width: '100%' }} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={(
              <span>
                违约赔率&nbsp;
                <Tooltip title="注:用户退网时,违约金=套餐总价*违约赔率">
                  <Icon type="question-circle-o" />
                </Tooltip>
              </span>
            )}
          >
            {getFieldDecorator('contractRate', {
              rules: [
                {
                  required: true, message: '请输入违约赔率',
                }],
            })(
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                max={1}
                step={0.01}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="简介"
          >
            {getFieldDecorator('packageDescription', {
            })(
              <Input.TextArea />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="业务说明"
          >
            {getFieldDecorator('serviceDescription', {
            })(
              <Input.TextArea />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="温馨提示"
          >
            {getFieldDecorator('packageAttention', {
            })(
              <Input.TextArea />
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">保存</Button>
          </FormItem>
        </Form>
      </Card>
    );
  }
}
